<template>
  <el-dialog
    :title="dataForm.attrId ? '修改':'新增' "
    :close-on-click-modal="false"
    @close="dialogClose"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="120px">

      <el-form-item label="属性名" prop="attrName">
        <el-input v-model="dataForm.attrName" placeholder="属性名"></el-input>
      </el-form-item>

      <el-form-item label="属性图标" prop="icon">
        <!--      <el-input v-model="dataForm.icon" placeholder="属性图标"></el-input>-->


        <upload-single-file @update-file="updateLogo($event)" ref="uploadSingleFileRef"
                            :fileListUrl="[dataForm.icon]"></upload-single-file>
<!--        dataForm.attrId === 0?null:-->
      </el-form-item>

      <el-form-item label="可选值列表" prop="valueSelect">
        <!--        <el-input v-model="dataForm.valueSelect" placeholder="可选值列表[用逗号分隔]"></el-input>-->

        <el-tag
          :key="tag"
          v-for="tag in dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{ tag }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
      </el-form-item>
      <el-form-item label="属性类型" prop="attrType">

        <!--        <el-input v-model="dataForm.attrType" placeholder="属性类型[0-销售属性，1-基本属性，2-既是销售属性又是基本属性]"></el-input>-->
        <el-select v-model="dataForm.attrType" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属分类" prop="catelogId">
        <!--        <el-input v-model="dataForm.catelogId" placeholder="所属分类"></el-input>-->
        <category-tree-cascader @category-change="categoryChangeMethod($event)"
                                ref="categoryTreeCascaderRef"
                                :categoryId="dataForm.catelogId"
        ></category-tree-cascader>
      </el-form-item>

      <el-form-item label="所属分组" prop="attrGroup" v-if="attrType===1">
        <el-select v-model="dataForm.attrGroupId" placeholder="请选择">
          <el-option
            v-for="item in attrGroupList"
            :key="item.attrGroupId"
            :label="item.attrGroupName"
            :value="item.attrGroupId">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="属性排序" prop="attrSort" v-if="attrType===1">
        <el-input-number v-model="dataForm.attrSort" :min="0"></el-input-number>
      </el-form-item>

      <el-form-item label="启用状态" prop="enable">
        <!--        <el-input v-model="dataForm.enable" placeholder="启用状态[0 - 禁用，1 - 启用]"></el-input>-->
        <el-tooltip :content="dataForm.enable===1?'启用': '禁用'" placement="top">
          <el-switch
            v-model="dataForm.enable"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-tooltip>
      </el-form-item>

      <el-form-item label="是否支持多选" prop="selectMultiple">

        <!--  <el-input v-model="dataForm.searchType" placeholder="是否需要检索[0-不需要，1-需要]"></el-input>
        -->

        <el-tooltip :content="dataForm.selectMultiple?'支持':'不支持'" placement="top">
          <el-switch
            v-model="dataForm.selectMultiple"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="true"
            :inactive-value="false">
          </el-switch>
        </el-tooltip>

      </el-form-item>
      <el-form-item label="是否需要检索" prop="searchType">

        <!--  <el-input v-model="dataForm.searchType" placeholder="是否需要检索[0-不需要，1-需要]"></el-input>
        -->

        <el-tooltip :content="dataForm.searchType===1?'检索':'不检索'" placement="top">
          <el-switch
            v-model="dataForm.searchType"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-tooltip>

      </el-form-item>
      <el-form-item label="快速展示" prop="showDesc">
        <!--        <el-input v-model="dataForm.showDesc" placeholder="快速展示【是否展示在介绍上；0-否 1-是】，在sku中仍然可以调整"></el-input>-->
        <el-tooltip :content="dataForm.showDesc===1?'展示在介绍上': '不展示在介绍上'" placement="top">
          <el-switch
            v-model="dataForm.showDesc"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-tooltip>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import uploadSingleFile from '../../../../components/upload/uploadSingleFile'
import categoryTreeCascader from '../../common/categoryTreeCascader'
import attrGroupApi from '../../../../api/product/attrGroupApi'

export default {
  props: ['attrTypeGlobal'],
  components: {
    uploadSingleFile,
    categoryTreeCascader
  },
  data () {
    return {
      visible: false,
      dataForm: {
        attrId: null,
        attrName: '',
        searchType: '',
        icon: '',
        valueSelect: '',
        attrType: '',
        enable: '',
        catelogId: '',
        showDesc: '',
        attrGroupId: null,
        attrSort: 0,
        selectMultiple:false
      },
      //dynamicTags: ['标签一', '标签二', '标签三'],
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      attrType: 1,
      // 可选值类型 [0-销售属性，1-基本属性，2-既是销售属性又是基本属性]
      options: [{
        value: 0,
        label: '销售属性'
      }, {
        value: 1,
        label: '基本属性'
      }, {
        value: 2,
        label: '既是销售属性又是基本属性'
      }],
      value: '',
      attrGroupList: [],

      dataRule: {
        attrName: [
          {required: true, message: '属性名不能为空', trigger: 'blur'}
        ],
        searchType: [
          {required: true, message: '是否需要检索[0-不需要，1-需要]不能为空', trigger: 'blur'}
        ],
        icon: [
          {required: true, message: '属性图标不能为空', trigger: 'blur'}
        ],
        /*valueSelect: [
          {required: true, message: '可选值列表[用逗号分隔]不能为空', trigger: 'blur'}
        ],*/
        attrType: [
          {required: true, message: '属性类型[0-销售属性，1-基本属性，2-既是销售属性又是基本属性]不能为空', trigger: 'blur'}
        ],
        enable: [
          {
            validator: (rule, value, callback) => {
              if (value === 0 || value === 1) {
                callback()
              }
              callback(new Error('启用状态只能是【0,1】'))
            }, trigger: 'blur'
          }
        ],
        catelogId: [
          {required: true, message: '所属分类不能为空', trigger: 'blur'}
        ],
        showDesc: [
          {required: true, message: '快速展示【是否展示在介绍上；0-否 1-是】，在sku中仍然可以调整不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    init (id) {
      this.dataForm.attrId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.attrId) {
          this.$http({
            url: this.$http.adornUrl(`/pms/attr/info/${this.dataForm.attrId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.attrName = data.attr.attrName
              this.dataForm.searchType = data.attr.searchType
              this.dataForm.icon = data.attr.icon
              // this.dataForm.valueSelect = data.attr.valueSelect
              this.dataForm.attrType = data.attr.attrType
              this.dataForm.enable = data.attr.enable
              this.dataForm.catelogId = data.attr.catelogId
              this.dataForm.showDesc = data.attr.showDesc

              this.dataForm.attrGroupId = data.attr.attrGroupId
              this.dataForm.attrSort = data.attr.attrSort
              this.dataForm.selectMultiple = data.attr.selectMultiple

              // 将字符串"a,b,c"拆解为数组 ['a','b','c']
              this.dynamicTags = data.attr.valueSelect.split(',').filter(v => {
                return v != ''
              })

              //console.log(this.dynamicTags)

              attrGroupApi.getAttrGroupPaginationByCondition(data.attr.catelogId).then(({data}) => {
                console.log(data.page.list)
                this.attrGroupList = data.page.list
              })
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/pms/attr/${!this.dataForm.attrId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'attrId': this.dataForm.attrId || undefined,
              'attrName': this.dataForm.attrName,
              'searchType': this.dataForm.searchType,
              'icon': this.dataForm.icon,
              'valueSelect': this.dynamicTags.join(','),
              'attrType': this.dataForm.attrType,
              'enable': this.dataForm.enable,
              'catelogId': this.dataForm.catelogId,
              'showDesc': this.dataForm.showDesc,
              'attrGroupId': this.dataForm.attrGroupId,
              'attrSort': this.dataForm.attrSort,
              'selectMultiple': this.dataForm.selectMultiple,
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    updateLogo (val) {
      console.log('父组件中的logo更新了', val)
      this.dataForm.icon = val
    },
    dialogClose () {

      this.$refs.uploadSingleFileRef.fileList = []
      //clearTimeout(this.$refs.uploadSingleFileRef.updatePolicyTimer);

      this.dynamicTags = []

      this.$refs.categoryTreeCascaderRef.categoryIdArrayLocal = []

      this.attrGroupList = []

      this.dataForm.attrGroupId = null
    },

    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm () {
      let inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    categoryChangeMethod (threeLevelCatId) {
      console.log(threeLevelCatId)
      this.dataForm.catelogId = threeLevelCatId[threeLevelCatId.length - 1]
      /**
       * 没有attrId，说明是新增
       * */
      if (!this.dataForm.attrId) {
        //新增要根据catelogId查询可选分组 attrAttrGroup
        attrGroupApi.getAttrGroupPaginationByCondition(this.dataForm.catelogId).then(({data}) => {

          this.attrGroupList = data.page.list

          console.log('catelogId选择之后，查询到的可选attrGroup', this.attrGroupList)

        })
      }
    },

    async getAttrGroupByCategoryId () {
      let p = await attrGroupApi.getAttrGroupPaginationByCondition(1)

      p.data
    }
  },
  watch: {
    attrTypeGlobal (val) {
      console.log('attrTypeGlobal更新了add-or-update', val)
      this.attrType = val
    }
  }
}
</script>
<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
